#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <time.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include "os_api.h"
#include "debug.h"
#include "i2c.h"

#define I2C_STACK_SIZE		(1024*3)

static void* i2c_task_stack = NULL;

static OSTaskRef i2c_task_ref = NULL;

#define I2C_SLAVE_ADDR      0x13  

static void i2c_task(void *ptr)
{
    unsigned char RegAddr, RegWriteValue, RegReadValue = 0;
    int ret;

	//int i2c_no = 1; // i2c2
	//int i2c_no = 3; // i2c4
	int i2c_no = 0; // i2c1
	int i2c_mode = STANDARD_MODE;
	
	ret = hal_I2cInit(i2c_no, i2c_mode);
	LOG_PRINTF("hal_I2cInit ret %d", ret);
	
	while(1){
		
		//---------------------
		//CHIP ID
		//---------------------
		RegAddr       = 0x00;
		//ret = hal_I2cRead(i2c_no, I2C_SLAVE_ADDR, RegAddr, &RegReadValue, 1);
		ret = hal_I2cReadEx(i2c_no, I2C_SLAVE_ADDR, &RegAddr, 1, &RegReadValue, 1);
		LOG_PRINTF("read i2c value=0x%x, ret=%d\n", RegReadValue, ret);

		//---------------------
		//Reset
		//---------------------
		RegAddr       = 0x36;
		RegWriteValue = 0xB6;
		//ret = hal_I2cWrite(i2c_no, I2C_SLAVE_ADDR, RegAddr, &RegWriteValue, 1);
		ret = hal_I2cWriteEx(i2c_no, I2C_SLAVE_ADDR, &RegAddr, 1, &RegWriteValue, 1);
		LOG_PRINTF("write i2c value=0x%x, ret=%d\n", RegWriteValue, ret);
	
		OSATaskSleep(5*200);
	}
}

int main(void)
{
    int ret;
	
	i2c_task_stack = malloc(I2C_STACK_SIZE);
	ASSERT(i2c_task_stack != NULL);
	
    ret = OSATaskCreate(&i2c_task_ref, i2c_task_stack, I2C_STACK_SIZE, 100, "i2c_task", i2c_task, NULL);
    ASSERT(ret == OS_SUCCESS);

	return 0;
}
